<?php
/**
 * Get.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/5/15
 * Time: 11:27
 */
namespace app\api\open\commodity;

use app\api\model\BrandModel;
use app\api\model\GoodsCategoryJoinModel;
use app\api\model\GoodsModel;
use app\api\model\GoodsRegionJoinModel;
use app\api\model\GoodsSpecModel;
use app\api\open\Base;
use app\api\open\member\Token;
use app\common\Singleton;
use think\Db;
use think\Hook;
use think\Validate;

class Get extends Token
{
    use Singleton;

    public function __construct($param = [])
    {
        try{
            parent::__construct($param);
        }catch (\Exception $e) {
            $this->member_id = null;
            $this->token_data = [];
        }
    }

    /**
     * @param array $param
     * @return array|false|null|\PDOStatement|string|\think\Model
     * @throws \Exception
     */
    public function index($param=[])
    {
        // 获取商品详情
        $info = GoodsModel::getInstance()->get(['id'=>$param['id']]);
        if(empty($info['id']))
        {
            throw new \Exception("查询结果为空",1);
        }
        // 获取商品规格
        $info['spec_list'] = GoodsSpecModel::getInstance()->getInfoByGoodsId($info['id']);

        if(empty($info['category_tree']))
        {
            $info['category_tree'] = ["","",""];
        }else{
            $info['category_tree'] = explode(",",trim($info['category_tree'],","));
        }
        if(empty($info['photo_list'])){
            $info['photo_list'] = [];
        }else{
            $info['photo_list'] = json_decode($info['photo_list'],true);
        }
        if(empty($info['attr_list'])){
            $info['attr_list'] = [];
        }else{
            $info['attr_list'] = json_decode($info['attr_list'],true);
        }
        if(empty($info['region_list'])){
            $info['region_list'] = [];
        }else{
            $info['region_list'] = json_decode($info['region_list'],true);
        }
        if(empty($info['spec_cols'])){
            $info['spec_cols'] = [];
        }else{
            $info['spec_cols'] = json_decode($info['spec_cols'],true);
        }

        foreach($info['spec_list'] as &$v)
        {
            if(empty($v['value'])){
                $v['value'] = [];
            }else{
                $v['value'] = json_decode($v['value'],true);
            }
        }

        // 建立监听
        if(!empty($this->member_id))
        {
            $listenData = [
                'member_id' => $this->member_id,
                'goods_id' => $info['id']
            ];
            Hook::listen("goods_browse",$listenData);
        }

        return $info;
    }
}